#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2018 crane <crane@crane-pc>
#
# Distributed under terms of the MIT license.

"""

"""

class Matric(object):
    __slot__ = ['n', 'sym_sum', 'sym_idx_sum', 'cur_value',]
    def __init__(self, n):
        self.n = n
        self.mat = self._create_mat()

        self.sym_sum = n ** 2 + 1   # 对称的两个数之和(左上角和右下角)mat[1,1] + mat[4,4]
        self.sym_idx_sum = n + 1    # 对称的两个数row之和(也是col之和): 比如[1, 1]和[4, 4]

        self.cur_value = 0          # 一个递增的数: 从1到n**2

        self.gene_matric()

    def gene_matric(self):
        self._gene_up_matric()
        self._gene_down_matric()
        self.show()

    def _gene_up_matric(self):
        for begin_row in range(1, self.n+1):
            for col in range(1, begin_row +1):
                self.cur_value += 1

                assign_col = col
                assign_row = begin_row + 1 - col
                self.mat[assign_row][assign_col] = self.cur_value
                # print("[%s][%s] ------> %s" % (assign_row, assign_col, mat[assign_row][assign_col]))

    def _gene_down_matric(self):
        # 通过上半部分求下半部分
        for row in range(1, self.n+1):
            for col in range(1, self.n+1):
                self._calc_sym_row_col(row, col)

    def _calc_sym_row_col(self, row, col):
        # 输入上半索引, 求下半对应的数
        # 计算[row][col] 对称的数大小
        if row + col > self.n:
            # 输入了下半部分, 因为上半部已经计算出来了, 直接返回
            return

        sym_row = self.sym_idx_sum - row
        sym_col = self.sym_idx_sum - col
        self.mat[sym_row][sym_col] = self.sym_sum - self.mat[row][col]

    def _create_mat(self):
        line = (self.n + 1) * [None]
        # mat = [line for i in range(self.n+1)]      # 错误, 每行都引用相同数组
        mat = [list(line) for i in range(self.n+1)]      # 不得已而为之, 创建二维数组
        return mat

    def show(self):
        for row in range(1, self.n+1):
            for col in range(1, self.n+1):
                print(self.mat[row][col], sep="  ", end=" ")

            print()


def main():
    print("start main")
    # mat = Matric(5)
    mat = Matric(5)
    # mat.show()

if __name__ == "__main__":
    main()
